<template>
	<uv-navbar title="学习报告" auto-back placeholder />
	<web-view :src="`${baseUrl}/student/report/learn-report.html?id=${id}&userId=${userId}&applet=1&student=1&${Math.random().toString().toString().slice(2, 5)}`"  @message="handlePostMessage" />
</template>

<script>
export default {
	data () {
		return {
			id: '',
			userId: ''
		}
	},
	
	onLoad({ id, userId }) {
		this.id = id;
		this.userId = userId;
	},
	
	mounted() {
		this.$nextTick(() => {
			let height = 0;
			let statusbar = 0;
			
			uni.createSelectorQuery()
				.in(this)
				.select('.uv-navbar')
				.boundingClientRect(rect => {
					uni.getSystemInfo({ // 获取当前设备的具体信息
						success: (sysinfo) => {
							statusbar = sysinfo.statusBarHeight + rect?.height / 2 + (sysinfo.screenWidth > 480 ? 20 : 0)
							height = sysinfo.windowHeight
						}
					});
					
					const currentWebview = this.$scope?.$getAppWebview?.();
					const wv = currentWebview?.children?.()?.[0];
					wv?.setStyle?.({
						top: statusbar,
						height: height - statusbar
					});
					
				})
				.exec();
		})
	},
	
	methods: {
		handlePostMessage({ detail }) {
			// #ifdef APP-PLUS | MP-WEIXIN
			uni.showLoading({ mask: true, title: '保存到相册中...' });
			// #endif
			
			// #ifdef APP-PLUS
			const bitmap = new plus.nativeObj.Bitmap("test");
			bitmap.loadBase64Data(
				detail.data[0]?.base64, 
				() => {
					const url = `_doc/${new Date().getTime()}.png`; 
					bitmap.save(url, { overwrite: true, }, () => {
						this.saveImageToPhotosAlbum(url, bitmap.clear);
					});
				}
			);
			// #endif
			
			// #ifdef MP-WEIXIN
			const systemManager = wx.getFileSystemManager();
			const filePath = `${wx.env.USER_DATA_PATH}/${new Date().getTime()}.png`
			systemManager.writeFile({
				filePath,
				encoding: 'base64',
				data: detail.data[0]?.base64,
				success: () => {
					uni.authorize({
						scope: "scope.writePhotosAlbum",
						success: () => {
							this.saveImageToPhotosAlbum(filePath);
						},
						fail: () => {
							uni.openSetting({
								success: result => {
									if (result.authSetting['scope.writePhotosAlbum']) {
										uni.showModal({
											showCancel: false,
											confirmText: '下载',
											content: '获取权限成功，再次点击下载按钮进行保存',
											success: ({ confirm }) => {
												if (confirm) this.saveImageToPhotosAlbum(filePath);
											}
										});
										
									} else {
										uni.showModal({
											title: '提示',
											showCancel: false,
											content: '获取权限失败，无法保存到相册哦~'
										});
									};
								},
								fail: error => {
									console.log("openSetting-error", error)
								},
							})
							uni.showToast({ title: '请先开启保存相册权限~', icon: 'none' });
						}
					});
				},
				fail: error => {
					uni.hideLoading();
					console.log('asystemManager.writeFile-error', error);
				}
			})
			// #endif
		}
	}
}
</script>